//Package cmd is a package for parsing command line parameters
//Copyright © 2020 Tim_Paik <timpaik@163.com>
package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/tim-paik/pdk/api"
)

// updateCmd represents the update command
var updateCmd = &cobra.Command{
	Use:     "update <URL>",
	Short:   "Update the repo",
	Long:    `Download and update the repo from the URL`,
	Aliases: []string{"u"},
	Run: func(cmd *cobra.Command, args []string) {
		name, err := cmd.Flags().GetString("name")
		if err != nil {
			fmt.Println(err)
		}

		if len(args) == 0 {
			err := api.UpdateLocal(name)
			if err != nil {
				fmt.Println(err)
			}
		} else if len(args) == 1 {
			err := api.Update(args[0], name)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			fmt.Println("Error: Too many targets specified!")
		}
	},
}

func init() {
	rootCmd.AddCommand(updateCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// updateCmd.PersistentFlags().String("foo", "", "A help for foo")
	updateCmd.PersistentFlags().String("name", "repo.json", "Update the repo'name")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// updateCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
